<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--任务管理数据-->
      <el-col>
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" >

          <el-form-item label="计划完成时间" prop="planCompletionStartTime" label-width="120px">
            <el-date-picker
              v-model="dateRange"
              clearable
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="被监督单位" prop="enterpriseName" label-width="120px">
            <el-input
              v-model="queryParams.enterpriseName"
              placeholder="请输入用户名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="监督人员" prop="supervisorId" label-width="120px">
            <el-select v-model="queryParams.supervisorId" clearable placeholder="请选择监督人员" @change="supervisorSelectChange">
              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="taskInfoList" @selection-change="handleSelectionChange">
          <el-table-column type="index" width="50" align="center" label="序号" />
          <el-table-column label="被监督单位" align="center" prop="enterpriseName" />
          <!--<el-table-column label="信用代码" align="center" prop="creditCode" />-->
          <el-table-column label="检查专业" align="center" prop="checkProfessionName" width="180px">
            <!--        <template slot-scope="scope">
                      <dict-tag :options="dict.type.enterprise_info_type" :value="scope.row.type"/>
                    </template>-->
          </el-table-column>
          <el-table-column label="镇/街道" align="center" prop="town" />
          <el-table-column label="经营地址" align="center" prop="addr" />
          <el-table-column label="监督机构" align="center" prop="superviseOrg" />
          <el-table-column label="监督员" align="center" prop="supervisor" />
          <el-table-column label="计划完成时间" align="center" prop="planCompletionTime" width="150px"/>
          <el-table-column label="执行状态" align="center" prop="implementStatus" >
            <template slot-scope="scope">
            <span style="margin-left: 10px">{{
              scope.row.status == "1"
                ? "执行中"
                : scope.row.status == "2"
                ? "已完成"
                : "未执行"
            }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
          <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="handleInfo(scope.row)"
              >查看详情</el-button>
          </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="75%" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-row>
          <!--<el-col :span="12">
            <el-form-item label="任务类型" prop="taskType">
              <el-select v-model="form.taskType" placeholder="请选择任务类型" style="width: 100%;" >
                <el-option
                  v-for="dict in dict.type.task_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>-->
          <el-col :span="12">
            <el-form-item label="计划完成时间" prop="planCompletionTime" label-width="150px">
              <el-date-picker
                v-model="enterpriseInfoForm.planCompletionTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="监督人员" prop="supervisorId" label-width="150px">
              <el-select v-model="enterpriseInfoForm.supervisorId" clearable placeholder="请选择监督人员" @change="supervisorSelectChange">
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="enterpriseInfoList" border @selection-change="enterpriseInfoSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="名称" align="center" prop="enterpriseName" />
          <el-table-column label="统一信用代码/登记号" align="center"  prop="creditCode"/>
          <el-table-column label="类型" align="center" prop="typeListName" width="180px">
            <!--        <template slot-scope="scope">
                      <dict-tag :options="dict.type.enterprise_info_type" :value="scope.row.type"/>
                    </template>-->
          </el-table-column>
         <el-table-column label="类别" align="center" prop="categoryListName"/>
          <el-table-column label="所在镇/街道" align="center" prop="town" />
          <el-table-column label="量化分级评定等级" align="center" prop="town2222222" />
          <el-table-column label="详细地址" align="center" prop="addr"/>
          <el-table-column label="联系电话" align="center" prop="contactNumber" />
        </el-table>

        <pagination
          v-show="enterpriseInfoTotal>0"
          :total="enterpriseInfoTotal"
          :page.sync="enterpriseInfoQueryParams.pageNum"
          :limit.sync="enterpriseInfoQueryParams.pageSize"
          @pagination="getList"
        />

        <el-table></el-table>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { doubleRandomPage, saveZpTaskInfoBatchDto } from "@/api/zhangping/taskInfo.js";
  import { taskInfoEnterpriseInfoList } from "@/api/zhangping/zpEnterpriseInfo";
  import { userList } from "@/api/system/user";
  import { getToken } from "@/utils/auth";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    name: "User",
    dicts: ['task_type','enterprise_category'],
    components: { Treeselect },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 总条数
        enterpriseInfoTotal: 0,
        // 弹出层标题
        title: "",
        // 部门树选项
        deptOptions: undefined,
        // 是否显示弹出层
        open: false,
        // 部门名称
        deptName: undefined,
        // 默认密码
        initPassword: undefined,
        // 日期范围
        dateRange: [],
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "label"
        },
        userList: [],
        taskInfoList: [],
        enterpriseInfoForm: {
          zpEnterpriseInfoIdList: [],
          planCompletionTime: undefined,
          supervisorId: undefined,
          supervisor: undefined,
        },
        enterpriseInfoQueryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        enterpriseInfoList: undefined,
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/system/user/importData"
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          planCompletionStartTime: undefined,
          planCompletionEndTime: undefined,
          enterpriseName: undefined,
          supervisorId: undefined
        },
      };
    },
    watch: {
      // 根据名称筛选部门树
      deptName(val) {
        this.$refs.tree.filter(val);
      }
    },
    created() {
      this.getList();
      this.getUserList()
    },
    methods: {
      /** 查询用户列表 */
      getList() {
        this.loading = true;
        if (this.dateRange){
          this.queryParams.planCompletionStartTime = this.dateRange[0]
          this.queryParams.planCompletionEndTime = this.dateRange[1]
        }else {
          this.queryParams.planCompletionStartTime = undefined
          this.queryParams.planCompletionEndTime = undefined
        }

        doubleRandomPage(this.queryParams).then(response => {
            this.taskInfoList = response.rows
            this.total = response.total;
            this.loading = false;
          }
        );
      },

      // 用户状态修改
      handleStatusChange(row) {
        let text = row.status === "0" ? "启用" : "停用";
        this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function() {
          return changeUserStatus(row.userId, row.status);
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {

        };
        this.resetForm("form");

        this.enterpriseInfoForm = {
          zpEnterpriseInfoIdList: [],
          planCompletionTime: undefined,
          supervisorId: undefined,
          supervisor: undefined,
        }
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.queryParams.deptId = undefined;
        this.$refs.tree.setCurrentKey(null);
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.userId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      // 多选框选中数据
      enterpriseInfoSelectionChange(selection) {

        console.log('enterpriseInfoSelectionChange', selection)
        this.enterpriseInfoForm.zpEnterpriseInfoIdList = selection.map(item => item.id);

      },

      supervisorSelectChange(val){

        //选中的数据和options进行匹配
        var obj={}
        obj= this.userList.find(function(i){
          return i.userId ===val
        })
        //在change中获取到整条对象数据
        this.enterpriseInfoForm.supervisor = obj.userName

      },
      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "handleResetPwd":
            this.handleResetPwd(row);
            break;
          case "handleAuthRole":
            this.handleAuthRole(row);
            break;
          default:
            break;
        }
      },
      handleInfo(){
             this.$router.push('/publicPlace/taskInfo/examineDetail')   
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加日常检查任务";
        this.getTaskInfoEnterpriseInfoList()
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const userId = row.userId || this.ids;
        getByUserId({userId: userId}).then(response => {
          this.form = response.data;
          if (this.form.dataPurviewType) {
            this.form.dataPurviewTypes =  this.form.dataPurviewType.split(",");
          }
          this.open = true;
          this.title = "修改用户";
          this.form.password = "";
        });
      },

      /** 提交按钮 */
      submitForm: function() {
        saveZpTaskInfoBatchDto(this.enterpriseInfoForm).then(response => {
          this.$modal.msgSuccess("添加成功");
          this.getList();
          this.open = false;
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        //const userIds = row.userId || this.ids;
        this.$modal.confirm('是否确认删除人员名称为"' + row.userName + '"的数据项？').then(function() {
          return delCoManager({userId: row.userId});
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },

      getUserList(){
        userList().then(response => {
          this.userList = response.data;
        });
      },

      getTaskInfoEnterpriseInfoList(){
        taskInfoEnterpriseInfoList(this.enterpriseInfoQueryParams).then(response => {
          this.enterpriseInfoList = response.rows
          this.enterpriseInfoTotal = response.data.total
        });
      }
    }
  };
</script>
